/**
 *加减数量
 * Created by 张栋 on 2016/10/20 15:10
 */
(function ($) {
    $.fn.plusready =function(options){
        return this.each(function(){
            var $this = $(this);
            $this.html("");
            var defaults = {
                min: 0,
                max: 10000,
                name: "num",
                defaultv: 0,
                callback:function (obj, num) {

                }
            };

            options=options||{};
            var dname = $this.attr("name");
            var dvalue = $this.attr("value");
            if(dname!=null){
                options.name = dname;
            }
            if(dvalue!=null){
                options.defaultv=dvalue;
            }

            var opt = $.extend(defaults, options);
            var checkmax =function (num) {
                return num < opt.max || opt.max==-1;
            };
            var checkekmin=function(num){
                return num > opt.min;
            };



            
            
            var $btn_plus = $("<button id='plus' class='pluMid'></button>"); 
            var $btn_minus = $("<button id='minus' class='pluMid' style='background-image: url(/res/images/oparaStatus/plus_06.png);'></button>");
            
            var $input = $("<input type='text' class='pluMidInp'/>");
            $input.val(opt.defaultv);
            $input.keyup(function () {
               var v = $(this).val();
                if(v==""){
                    v="0";
                }

                v = v.replace(/[^\d\.]/g,'0');
                var truev =0;//真实数值
                if(/^[0-9]*\.$/.test(v)){
                    truev=parseFloat(v);
                }else{
                    v = parseFloat(v);
                    truev =v;
                }

                if(!checkekmin(truev)){
                    truev=opt.min;
                }
                if(!checkmax(v)){
                    truev=opt.max;
                }
                $this.attr("value",truev);
                $(this).val(v);
                opt.callback($this,truev);

            });


            $this.append($btn_minus);
            $this.append($input);
            $this.append($btn_plus);



            $btn_plus.click(function () {
                var num = parseInt($input.val());
                if(checkmax(num)){
                    num++;
                    $input.val(num);
                    $this.attr("value",num);
                    opt.callback($this,num);
                };

            });

            $btn_minus.click(function () {
                var num = parseInt($input.val());
                if(checkekmin(num)){
                    num--;
                    $input.val(num);
                    $this.attr("value",num);
                    opt.callback($this,num);
                }
            });
        })
    };




})(jQuery);